<?php
require "../../../../framework/bootstrap.inc.php";
require "Config.php";
require "OAuth_Client.php";
require "util.php";
require "RpcClient.php";
require "RpcService.php";
require "OrderService.php";
$isseting=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_systemsetting')." order by id asc limit 1");
$app_key = $isseting["elem_key"];
$app_secret = $isseting["elem_secret"];
$sandbox = $isseting['elemdebug'] ? true : false;
$scope = "all";
$config = new Config($app_key, $app_secret, $sandbox);

/**/
$content = file_get_contents("php://input");
$response = array("message" => "ok");
if ($content == null) {
    echo json_encode($response);
    return;
}
$message = convert_to_message($content);
$result = check_signature($message, $config->get_app_secret());
if ($result == false) {
    echo "invalid signature";
    return;
}
echo json_encode($response);
//$msgType=array(10=>"订单生效",12=>"商户接单",14=>"订单被取消",15=>"订单置为无效",17=>"订单强制无效",18=>"订单完结",20=>"用户申请取消单",21=>"用户取消取消单申请",22=>"商户拒绝取消单",23=>"商户同意取消单",24=>"用户申请仲裁取消单",25=>"客服仲裁取消单申请有效",26=>"客服仲裁取消单申请无效",30=>"用户申请退单",31=>"用户取消退单",32=>"商户拒绝退单",33=>"商户同意退单",34=>"用户申请仲裁",35=>"客服仲裁退单有效",36=>"客服仲裁退单无效",45=>"用户催单",46=>"商家回复用户催单",51=>"订单待分配配送商",52=>"订单待分配配送员",53=>"配送员取餐中",54=>"配送员已到店",55=>"配送员配送中",56=>"配送成功",57=>"配送取消，商户取消",58=>"配送取消，用户取消",59=>"配送取消，物流系统取消",60=>"配送失败，呼叫配送晚",61=>"配送失败，餐厅出餐问题",62=>"配送失败，商户中断配送",63=>"配送失败，用户不接电话",64=>"配送失败，用户退单",65=>"配送失败，用户地址错误",66=>"配送失败，超出服务范围",67=>"配送失败，骑手标记异常",68=>"配送失败，系统自动标记异常",69=>"配送失败，其他异常",70=>"配送失败，超时标记异常",71=>"自行配送",72=>"不再配送",73=>"物流拒单，仅支持在线支付",74=>"物流拒单，超出服务范围",75=>"物流拒单，请求配送晚",76=>"物流拒单，系统异常",91=>"店铺营业状态通知",92=>"店铺有效性通知",100=>"应用授权解除通知",105=>"服务订单订购通知");
switch($message["type"]){
    case 10:
        $userId = $message["userId"];
        $tokenItem = get_token_by_shopid($message["shopId"]);
        if(TIMESTAMP>$tokenItem->expires_in){
            $client=new OAuth_Client($config);
            $returnstr = $client->get_token_by_refresh_token($tokenItem->refresh_token, "all");
            $token=$returnstr->access_token;
            $data=array(
                "access_token"=>$returnstr->access_token,
                "expires_in"=>($returnstr->expires_in)+TIMESTAMP,
                "refresh_token"=>$returnstr->refresh_token,
            );
            pdo_update("j_hmoney_elemtoken",$data,array("shopid"=>$message["shopId"]));
        }else{
            $token=$tokenItem;
        }
        if ($token == null) die("获取token错误");
        $order_service = new OrderService($token,$config);
        $order = json_decode($message["message"]);
        $order_service->confirm_order($order->id);
        $isNew=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_takeoutorder')." where orderid=:a",array(":a"=>$message['orderId']));
        if($isNew)return;
        $data=array(
            "platform"=>1,
            "userId"=>$order->userId,
            "shopid"=>$order->shopId,
            "orderid"=>$order->id,
            "createtime"=>strtotime($order->createdAt),
            "activetime"=>strtotime($order->activeAt),
            "deliverFee"=>format_price($order->deliverFee),
            "description"=>$order->description,
            "mobile"=>implode(",",$order->phoneList),
            "status"=>$order->status,
            "refundStatus"=>$order->refundStatus,
            "totalPrice"=>format_price($order->totalPrice),
            "originalPrice"=>format_price($order->originalPrice),
            "realname"=>$order->consignee,
            "deliveryGeo"=>$order->deliveryGeo,
            "deliveryPoiAddress"=>$order->deliveryPoiAddress,
            "income"=>format_price($order->income),
            "serviceRate"=>format_price($order->serviceRate),
            "serviceFee"=>format_price($order->serviceFee),
            "hongbao"=>format_price($order->hongbao),
            "packageFee"=>format_price($order->packageFee),
            "activityTotal"=>format_price($order->activityTotal),
            "shopPart"=>format_price($order->shopPart),
            "elemePart"=>format_price($order->elemePart),
            "VipDeliveryFeeDiscount"=>format_price($order->vipDeliveryFeeDiscount),
            "cancelOrderDescription"=>$order->cancelOrderDescription,
            "cancelOrderCreatedAt"=>$order->cancelOrderCreatedAt,
        );
        pdo_insert("j_hmoney_takeoutorder",$data);
        $goodsbox=$order->groups;
        foreach($goodsbox as $goodslist){
            foreach($goodslist->items as $goods){
                $gooddata=array(
                    "orderid"=>$order->id,
                    "shopid"=>$message['shopId'],
                    "goodid"=>$goods->id,
                    "skuid"=>$goods->skuId,
                    "title"=>$goods->name,
                    "pcate"=>$goods->categoryId,
                    "price"=>format_price($goods->price),
                    "quantity"=>$goods->quantity,
                    "total"=>format_price($goods->total),
                    "userprice"=>format_price($goods->userPrice),
                    "shopprice"=>$goods->shopPrice,
                    "additions"=>implode(",",$goods->additions),
                    "newspecs"=>implode(",",$goods->newSpecs),
                    "attributes"=>implode(",",$goods->attributes),
                );
                pdo_insert("j_hmoney_takeoutordergoods",$gooddata);
            }
        }
        wildDog_socket($message["shopId"],$order->id);
        break;
}

/*
 {
  "{"requestId":"200008486196596798","type":10,"
message":"{"id":"3016142318666167311","orderId":"3016142318666167311","address":"东平国家森林公园三单元四楼五室","createdAt":"2017-12-03T15:04:55","activeAt":"2017-12-03T15:04:55","deliverFee":0.01,"deliverTime":null,"description":"",

"groups":[{"name":"1号篮子","type":"normal","items":[{"id":1327369753,"skuId":200000130426627134,"name":"Tset蛋面3","categoryId":1,"price":0.13,"quantity":1,"total":0.13,"additions":[],"newSpecs":[],"attributes":[],"extendCode":"","barCode":"","weight":1.0,"userPrice":0.0,"shopPrice":0.0,"vfoodId":1315186503},{"id":1327369742,"skuId":200000130426615870,"name":"Tset蛋面2","categoryId":1,"price":0.11,"quantity":1,"total":0.11,"additions":[],"newSpecs":[],"attributes":[],"extendCode":"","barCode":"","weight":1.0,"userPrice":0.0,"shopPrice":0.0,"vfoodId":1315186493}]}],

"invoice":null,"book":false,"onlinePaid":true,"railwayAddress":null,"phoneList":["13751858196"],"shopId":159253207,"shopName":"云门店收银台测试店铺","daySn":1,"status":"unprocessed","refundStatus":"noRefund","userId":568810346,"totalPrice":0.25,"originalPrice":0.25,"consignee":"吴先生 先生","deliveryGeo":"121.48234,31.67892","deliveryPoiAddress":"东平国家森林公园三单元四楼五室","invoiced":false,"income":0.25,"serviceRate":0.0,"serviceFee":-0.0,"hongbao":0.0,"packageFee":0.0,"activityTotal":-0.0,"shopPart":-0.0,"elemePart":-0.0,"downgraded":false,"vipDeliveryFeeDiscount":0.0,"openId":"","secretPhoneExpireTime":null,"orderActivities":[],"invoiceType":null,"taxpayerId":"","coldBoxFee":0.0,"cancelOrderDescription":null,"cancelOrderCreatedAt":null}",

"shopId":159253207,"userId":568810346,"timestamp":1512284815000,"orderId":"3016142318666167311"}"
}*/
